package se.wobbia.android.blog;

import se.wobbia.android.data.GlobalResources;
import se.wobbia.android.net.UploadTask;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

public class UploadPage extends Activity implements OnClickListener {
	PercentProgressUpdateReceiver m_update_receiver ;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.uploadpage);
		Button startUploadBtn = (Button)findViewById(R.id.startUploadBtn);
		startUploadBtn.setOnClickListener(this);
		
		bindTransferServiceReceiver();
	}

	private void bindTransferServiceReceiver() {
		// TODO Auto-generated method stub
		m_update_receiver= new PercentProgressUpdateReceiver();
		if (m_update_receiver != null) {
			this.registerReceiver(m_update_receiver, new IntentFilter(GlobalResources.INTENT_UPLOAD_PROGRESS_UPDATE));			
		}
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		String file  = "/data/app/com.tieto-2.apk";
		addUpload(file);
	}

	public void addUpload(String file) {
		Bundle bundle =  new Bundle();
		bundle.putString("file", file);
		bundle.putString("url", GlobalResources.UPLOAD_URL);
		UploadTask uploadTask = new UploadTask(getApplicationContext());
		uploadTask.addUpload(bundle);
		uploadTask.execute();
	}

	// This is the receiver that we use to update the percentage progress display
    // for the current upload and/or download.
	public class PercentProgressUpdateReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			ProgressBar progressBar = (ProgressBar)findViewById(R.id.transferProgressBar);
			Bundle extras = intent.getExtras();
			int percent = extras.getInt("percent");
			if (progressBar != null) {
				progressBar.setVisibility(View.VISIBLE);
				progressBar.setProgress(percent);
        	}
		}
	}
}
